package cn.adair.wechat;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;

import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.openapi.IWXAPI;

import java.io.ByteArrayOutputStream;
import java.util.List;

public class WeChatUtil {

    /**
     * 是否安装了微信
     */
    public static boolean isWxAppInstalled(Context context) {
        WeChat wechat = WeChat.instance();
        IWXAPI wxApi = wechat.mWxApi;
        boolean bIsWxAppInstalled = wxApi.isWXAppInstalled();
        if (!bIsWxAppInstalled) {
            final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
            List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    public static boolean isWxAppInstalledAndSupported(Context context) {
        WeChat wechat = WeChat.instance();
        IWXAPI wxApi = wechat.mWxApi;
        boolean bIsWxAppInstalled = isWxAppInstalled(context);
        if (!bIsWxAppInstalled) {
            //未安装微信
            return false;
        }
        if (wxApi.getWXAppSupportAPI() < Build.PAY_SUPPORTED_SDK_INT) {
            // 微信版本需升级
            return false;
        }
        return true;
    }


    public static byte[] bmpToByteArray(final Bitmap bmp, final boolean needRecycle) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, output);
        if (needRecycle) {
            bmp.recycle();
        }

        byte[] result = output.toByteArray();
        try {
            output.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }

}
